#include "sqstack.h"

PSeqStack createEmptyStack(int m)
{
    PSeqStack pstack;
  
    if (m < 0)
    {
        return NULL;
    }

    pstack = (PSeqStack) malloc(sizeof(struct stStack));

    if (pstack != NULL)
    {
        pstack->buffer = (ELEMTYPE *) malloc(sizeof(ELEMTYPE)*m);
        if (pstack->buffer == NULL)
        {
            free (pstack);
            return NULL;
        }

        pstack->MAXNUM = m;
        pstack->top = BUTTOM;
        pstack->length = 0;

        return pstack;
    }
    
    return NULL;
}

int isEmpty(PSeqStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    return (pstack->length == 0);
}

int isFull(PSeqStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    return (pstack->length == pstack->MAXNUM);
}

int push(PSeqStack pstack, ELEMTYPE x)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    if (isFull(pstack) == 1)
    {
        return 0;
    }
    
    pstack->top++;
    pstack->buffer[pstack->top] = x;
    pstack->length++;
    return 1;
}

int pop(PSeqStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    if (isEmpty(pstack) == 1)
    {
        return 0;
    }
    
    pstack->top--;
    pstack->length--;
    
    return 1;
}

int top(PSeqStack pstack, ELEMTYPE *x)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    if (isEmpty(pstack) == 1)
    {
        return 0;
    }
    
    *x = pstack->buffer[pstack->top];
    return 1;
}

SIZE_T length(PSeqStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    return pstack->length;
}

int empty(PSeqStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    pstack->top = BUTTOM;
    pstack->length = 0;
}

int destroy(PSeqStack *pstack)
{
    if (*pstack != NULL)
    {
        free((*pstack)->buffer);
        free(*pstack);
        *pstack = NULL;
        return 1;
    }

    return -1;
}

int printStack(PSeqStack pstack)
{
    SIZE_T i;
    POSITION t;

    if (pstack != NULL)
    {
        t = pstack->top;
        i = pstack->MAXNUM;
        printf("=============== STACK ===============\n");
        printf("============ %d ELEMENTS =============\n", pstack->length);
        while (i >= 0)
        {
            if (i > t)
            {
                printf("BUFFER[%d] = --\n", i);
            }
            else
            {
                printf("BUFFER[%d] = %c\n", i, pstack->buffer[i]);
            }
            i--;
        }
        return 1;
    }
    
    return -1;
}
